<template>
  <div id="app">
    <router-view ref="{router}" />
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { debounce } from './utils';

const updateRoute = debounce((readingTime, startAnswerTime, endAnswerTime) => {
  if (
    readingTime === undefined ||
    startAnswerTime === undefined ||
    endAnswerTime === undefined
  ) {
    return;
  }
  const current = Date.now();
  const href = window.location.href.split('#')[1];
  // console.log(current, readingTime, startAnswerTime, endAnswerTime);
  if (+current < +readingTime) {
    if (href !== '/' && href !== '/rules') window.location.replace('/#/');
  } else if (+current < +startAnswerTime) {
    if (href !== '/read' && href !== '/' && href !== '/rules') {
      window.location.replace('/#/read');
    }
  } else if (+current < +endAnswerTime) {
    if (
      href !== '/quiz' &&
      href !== '/countdown' &&
      href !== '/' &&
      href !== '/rules'
    ) {
      window.location.replace('/#/quiz');
    }
  } else if (
    href !== '/rank' &&
      href !== '/certificate' &&
      href !== '/' &&
      href !== '/rules'
  ) {
    window.location.replace('/#/rank');
  }
}, 1000);

export default {
  name: 'App',
  data: () => ({
    readingTime: undefined,
    startAnswerTime: undefined,
    endAnswerTime: undefined,
  }),
  mounted() {
    this.readingTime = new Date(this.READING_TIME);
    this.startAnswerTime = new Date(this.START_ANSWER_TIME);
    this.endAnswerTime = new Date(this.END_ANSWER_TIME);
    updateRoute(this.readingTime, this.startAnswerTime, this.endAnswerTime);
    setInterval(
      () =>
        updateRoute(this.readingTime, this.startAnswerTime, this.endAnswerTime),
      10000,
    );
  },
  updated() {
    updateRoute(this.readingTime, this.startAnswerTime, this.endAnswerTime);
  },
  computed: {
    ...mapState(['READING_TIME', 'START_ANSWER_TIME', 'END_ANSWER_TIME']),
  },
};
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  font-size: 16px;
}
div.el-select-dropdown {
  width: 180px;
}
.el-message {
  min-width: 90vw !important;
}
</style>
